/*
 *  Licensed to PECATS under one or more contributor license agreements below:
 *  1. http://www.mozilla.org/MPL/MPL-1.1.html
 *  2. http://www.gnu.org/licenses/gpl-2.0.html
 *  3. http://www.gnu.org/licenses/lgpl-2.1.html
*/

/* *************************************************************
*  Servlet for Handling Financial Payments
*  Name: PaymentManagerServlet.java
*  Author: www.pecats.com
*  Date: Sept 15, 2008
*  THIS PROGRAM IS UNDER CONSTRUCTION AND WOULD BE UPDATED SOON
***************************************************************/

package com.pecats.server.core;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletConfig;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStreamReader;

import java.util.Enumeration;
import java.net.URL;
import java.net.URLEncoder;
import java.net.URLConnection;

import com.pecats.server.core.CustomerAccountManager;
import com.pecats.server.core.Account;

/**
 * Servlet used to manage payment related request from the customer
 */

public class PaymentManagerServlet extends HttpServlet 
{

    /*
     * Method used to handle incoming http request.
     * @param request HttpServletRequest object from the incoming request
     * @param response HttpServletResponse object which forms the response
     * @exception ServletException
     * @exception IOException
    */
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException 
	{

		try
		{
	            // Handle actions

			// read post from PayPal system and add 'cmd'
			Enumeration en = request.getParameterNames();
			String str = "cmd=_notify-synch";
			while(en.hasMoreElements())
			{
				String paramName = (String)en.nextElement();
				String paramValue = request.getParameter(paramName);
				str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
			}

			String auth_token = "V-B0qZ4jS-xve52ZkK0Nl-AruJ47vStmYso1VVjsU1U_YM3IWXv2noUhNWu";
			str = str + "&at=" + auth_token;

			// post back to PayPal system to validate
			// NOTE: change http: to https: in the following URL to verify using SSL (for increased security).
			// using HTTPS requires either Java 1.4 or greater, or Java Secure Socket Extension (JSSE)
			// and configured for older versions.
			
			URL u = new URL("https://www.sandbox.paypal.com/cgi-bin/webscr");
			URLConnection uc = u.openConnection();
			uc.setDoOutput(true);
			uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			PrintWriter pw = new PrintWriter(uc.getOutputStream());
			pw.println(str);
			pw.close();

			BufferedReader in = new BufferedReader(
			new InputStreamReader(uc.getInputStream()));
			String res = in.readLine();
			
/*			out.println("el status es: "+ res);
			out.println("string: "+ str);
*/			
			String [] temp = null;
			String message = "";
			
			if (res.equals("SUCCESS"))
			{
				while ( (res=in.readLine()) != null )
				{
					temp = res.split("=");
					if (temp[0].equals("address_name"))
					{
						message = message + "<b>Customer Name:</b> " + temp[1] + "<br>";
					}
	
					if (temp[0].equals("item_name"))
					{
						message = message + "<b>Item Name: </b>" + temp[1] + "<br>";
					}
					if (temp[0].equals("mc_gross"))
					{
						message = message + "<b>Amount: </b>" + temp[1] + "<br>";
					}
				};
			}
			else if(res.equals("FAIL"))
			{
//				out.println("Please check the error log. The transaction has a Fail response");
			}
			in.close();

			
/*			CustomerAccountManager customManager;

			//check notification validation
			if(res.equals("VERIFIED")) 
			{
				// check that paymentStatus=Completed
				// check that txnId has not been previously processed
				// check that receiverEmail is your Primary PayPal email
				// check that paymentAmount/paymentCurrency are correct
				// process payment
			
				customManager = new CustomerAccountManager();
				customManager.updateAccount(payerEmail, txnId, "Y");

			}
			else if(res.equals("INVALID")) 
			{
				// log for investigation

				customManager = new CustomerAccountManager();
				customManager.updateAccount(payerEmail, txnId, "INVALID");
			}
			else {
				// error
			}
*/

			request.setAttribute("loginmessage", "Thank You - Payment Successfully Done, Please login to upload a file");
						
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/LoginJSP.jsp");		
			dispatcher.forward(request, response);

            } 
		catch (Exception ex) 
		{
            	throw new ServletException(ex);
        	}
	}

}

